﻿using System;
using HK.Core.Common.Data;
using UnityEngine;

namespace HK.Core.Utils
{
    /// <summary>
    /// 工具类 : Json
    /// </summary>
    public static class UtilsJson<TJson> where TJson : JsonData
    {
        /// <summary>
        /// 将Json字符串转换成对象.
        /// </summary>
        /// <returns>对象.</returns>
        /// <param name="iJsonStr">Json字符串.</param>
        public static TJson ConvertFromJsonString(string iJsonStr)
        {
            var objRet = default(TJson);

#if UNITY_EDITOR
            try
            {
#endif
                objRet = string.IsNullOrEmpty (iJsonStr) ? default(TJson) : JsonUtility.FromJson<TJson>(iJsonStr);
#if UNITY_EDITOR
            }
            catch (Exception exp)
            {
                Debug.LogError($"UtilsJson::ConvertFromJsonString():Target:{typeof(TJson).Name}" +
                            $"\n  JsonStr:{iJsonStr} Error:{exp.Message} Exception:{exp.GetType().Name}" +
                            $"\n  StackTrace:{exp.StackTrace}");
            }
#endif
            return objRet;
        }

        /// <summary>
        /// 将对象转换成Json字符串.
        /// </summary>
        /// <param name="iJson">Json对象.</param>
        /// <param name="iPretty">If true, format the output for readability. If false, format the output for minimum size. Default is false.</param>
        /// <returns>Json字符串.</returns>
        public static string ConvertToJsonString(TJson iJson, bool iPretty = true)
        {
            string strRet = null;
            
#if UNITY_EDITOR
            try
            {
#endif
                strRet =  (null == iJson || !iJson.Valid) ? null : JsonUtility.ToJson(iJson, iPretty);
#if UNITY_EDITOR
            }
            catch (Exception exp)
            {
                Debug.LogError($"UtilsJson::ConvertFromJsonString():Target:{typeof(TJson).Name} " +
                               $"\n  Error:{exp.Message} Exception:{exp.GetType().Name}" +
                               $"\n  StackTrace:{exp.StackTrace}");
            }
#endif
            return strRet;
        }
    }
}
